package cn.sinjet.utils;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.mgroup.wazehelper.R;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.widget.RemoteViews;
import cn.sinjet.entity.UpgradeInfo;
public class UpgradeUtil {
	final String tag = "upgrade";
//    String apkUrl;
    File file = null;
    Context context;
    UpgradeInfo upgradeInfo = null;
    public UpgradeUtil(Context context){
    	this.context = context;
    }
	public  int haveNewVersion(String url) {
		// TODO Auto-generated method stub
		//apkUrl = "http://120.24.64.247/upgrade/Toure.apk";
		upgradeInfo = getUpdateInfo(url);
		if(upgradeInfo == null)
			return 0;
		try {
			PackageInfo packInfo;
			packInfo = context.getPackageManager().getPackageInfo(context.getPackageName(),0);
			int versionCode = packInfo.versionCode;
			if(upgradeInfo.vcode >versionCode)
			    return 1;
			else 
				return 2;
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return 0;
		}
	}

	public int getServiceMCUVersion(String url) {
		upgradeInfo = getUpdateInfo(url);
		if (upgradeInfo == null)
			return 0;
		else
			return upgradeInfo.vcode;
	}

	public int downloadNewMCU(String urlPath,String fileName) {
		try {
			if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
				return 1;
			URL url = new URL(urlPath);
			HttpURLConnection conn =  (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);
			int totalSize = conn.getContentLength();
			Log.d(tag, "total size:"+totalSize);
			InputStream is = conn.getInputStream();
			file = new File(Environment.getExternalStorageDirectory(), fileName);
			FileOutputStream fos = new FileOutputStream(file);
			BufferedInputStream bis = new BufferedInputStream(is);
			byte[] buffer = new byte[1024];
			int len ;
			int total=0;
			while((len =bis.read(buffer))!=-1){
				fos.write(buffer, 0, len);
				total+= len;
			}
			fos.close();
			bis.close();
			is.close();
		}catch(Exception e){
			e.printStackTrace();
			return -1;
		}
		return 0;
	}
	
	public int downloadNewApk(String path) {
		// TODO Auto-generated method stub
		try{
			if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
				return 1;
			URL url = new URL(path);
			HttpURLConnection conn =  (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);
			//��ȡ���ļ��Ĵ�С 
			//pd.setMax(conn.getContentLength());
			int totalSize = conn.getContentLength();
			Log.d(tag, "total size:"+totalSize);
			InputStream is = conn.getInputStream();
			file = new File(Environment.getExternalStorageDirectory(), "new-HudNavi.apk");
			FileOutputStream fos = new FileOutputStream(file);
			BufferedInputStream bis = new BufferedInputStream(is);
			byte[] buffer = new byte[1024];
			int len ;
			int total=0;
			while((len =bis.read(buffer))!=-1){
				fos.write(buffer, 0, len);
				total+= len;
				//pd.setProgress(total);
				//Log.d(tag, "progress:"+total);
				showProgressNotification(totalSize,total);
			}
			fos.close();
			bis.close();
			is.close();
		}catch(Exception e){
			e.printStackTrace();
			if(mNotificationManager != null)
			mNotificationManager.cancel(0);
			return -1;
		}
		if(mNotificationManager != null)
			mNotificationManager.cancel(0);
		return 0;
	}

	private NotificationManager mNotificationManager = null;
	private Notification mNotification = null;
	int oldResult = 0;
	public void showProgressNotification(int fileSize,int downLoadFileSize){
		int result = downLoadFileSize * 100 / fileSize;
		if(oldResult == result)
			return;
		oldResult = result;
		Log.d("upgrade", "progress:"+result);
		if(mNotification == null || mNotificationManager == null){
			mNotificationManager = (NotificationManager)context
					.getSystemService(Context.NOTIFICATION_SERVICE);
			mNotification = new Notification();
			mNotification.icon = R.drawable.ic_launcher_sinjet;
			mNotification.tickerText = "开始下载";
			mNotification.contentView = new RemoteViews(context.getPackageName(),R.layout.notification_view);
//			mNotification.contentIntent = ;
		}
		mNotification.contentView.setTextViewText(R.id.content_view_text, result + "%");
	    mNotification.contentView.setProgressBar(R.id.content_view_progress, fileSize, downLoadFileSize, false);
	    mNotificationManager.notify(0, mNotification);
	    if(result>=100)
	    	mNotificationManager.cancel(0);
	}
	/*
	   jsonObj.put("version", "v3.1");
    	jsonObj.put("date", "2015-11-26");
    	jsonObj.put("changed", "1.�����̳����� 2.�����Զ���������¹���??? 3.�����������???");
    	jsonObj.put("md5", "12345678901234567");
    	jsonObj.put("url", "http://120.24.64.247/upgrade/Toure.apk");
	 */
	
//    public void getUpdateInfo(){
//    	
//    }
	
	public UpgradeInfo getUpgradeInfo(){
		return upgradeInfo;
	}
	private UpgradeInfo getUpdateInfo(String url){
		try {
			HttpGet request = new HttpGet(url);
			HttpResponse httpResponse = new DefaultHttpClient().execute(request);
			String retStr = EntityUtils.toString(httpResponse.getEntity());
			
			JSONObject result = new JSONObject(retStr);
			int vcode = result.getInt("vcode");
			String vname = result.getString("vname");
			String date = result.getString("date");
			String changed = result.getString("changed");
			String downloadUrl = result.getString("url");
			String md5 = result.getString("md5");
			Log.d(tag, "json:"+vname+" "+date+" "+changed);
			
			UpgradeInfo upgradeInfo = new UpgradeInfo();
			upgradeInfo.vcode = vcode;
			upgradeInfo.vname = vname;
			upgradeInfo.date = date;
			upgradeInfo.updateContent = changed;
			upgradeInfo.md5 = md5;
			upgradeInfo.downloadUrl = downloadUrl;
			return upgradeInfo;
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	public void installApk() {
		// TODO Auto-generated method stub
		Intent intent = new Intent();  
		intent.setAction(Intent.ACTION_VIEW);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");  
		context.startActivity(intent);  
	}
    
}
